package com.littleHan.brushQuestions.web.start.service.impl;

import com.littleHan.brushQuestions.web.start.dao.*;
import com.littleHan.brushQuestions.web.start.pojo.*;
import com.littleHan.brushQuestions.web.start.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private GeneralUserDao generalUserDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private PermissionDao permissionDao;
    @Override
    public List<Permission> getPermission(String username) {
        //用username去普通用户表里取出其id
        GeneralUser generalUser=generalUserDao.getGeneralUserByUsername(username);
        //根据普通用户表的id，去用户表取出id
        User user=userDao.getUserByGeneralUserId(generalUser.getId());
        //根据userId去role表获取角色
        List<UserRole>userRoleList=userRoleDao.getRoleByUserId(user.getId());
        //根据取得的roleId去role表里获得角色信息
        List<Role> roleList=roleDao.getRoleById(userRoleList);
        //根据roleId去角色权限表获得其权限id
        List<RolePermission> rolePermissionList=rolePermissionDao.getRolePermissionByRoleId(roleList);
        //根据permissionId去权限表获取
        List<Permission> permissionList=permissionDao.getPermissionById(rolePermissionList);
        return permissionList;
    }

    @Override
    public boolean getPermissionListAndJudge(String userId,String url) {
        //根据userId去role表获取角色
        List<UserRole>userRoleList=userRoleDao.getRoleByUserId(userId);
        //根据取得的roleId去role表里获得角色信息
        List<Role> roleList=roleDao.getRoleById(userRoleList);
        //根据roleId去角色权限表获得其权限id
        List<RolePermission> rolePermissionList=rolePermissionDao.getRolePermissionByRoleId(roleList);
        //根据permissionId去权限表获取
        List<Permission> permissionList=permissionDao.getPermissionById(rolePermissionList);
        int flag=0;
        //如果访问的路径包含数据库中权限表中的路径那么就通过
        for(Permission p:permissionList){
            String getPath=p.getPath();
            String []name=getPath.split(";");
            for(int i = 0; i < name.length; i++){
                if(url.indexOf(name[i])!=-1){
                    flag++;
                }
            }
        }
        if(flag!=0){
            return true;
        }
        return false;
    }

    @Override
    public boolean isAccountBan(String userId) {
        //根据用户表获取其普通用户id，然后再去普通用户表里查看状态是否是0，如果为0则就封禁状态 返回false
        int violation=generalUserDao.isAccountBan(userId);
        if(violation==1){ //1就打回true说明没有被封禁
            return true;
        }
        return false;
    }
}
